using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Brick : MonoBehaviour
{
   public SpriteRenderer spriteRenderer {get; private set;}
   public Sprite[] states;
   public int point = 100;
   public int health { get; private set; }
   public bool unbreakable;

   public enum Brickprop_Type
   {
      Normal,
      Prop_Life,//生命道具
      Prop_More //多球道具
   }
   public Brickprop_Type currType;
   public int brickLayer=0;
   public GameObject propPrefab;//道具预制体

   private void Awake()
   {
      spriteRenderer = this.GetComponent<SpriteRenderer>();
   }

   private void Start()
   {
      RestBrick();
   }

   /// <summary>
   /// 重置砖块
   /// </summary>
   public void RestBrick()
   {
      this.gameObject.SetActive(true);
      if (!this.unbreakable)
      {
         this.health = this.states.Length;
         this.spriteRenderer.sprite = this.states[this.health-1];
      }
   }

   private void Hit()
   {
      if (this.unbreakable)
      {
         return;
      }
      this.health--;
      if (this.health<=0)
      {
         this.gameObject.SetActive(false);
      }
      else
      {
         this.spriteRenderer.sprite = this.states[this.health-1];
         OnHit();
      }
      
      //设置分数
      GameManager.Instance.OnBrickHit(this);
   }

   protected virtual void OnHit()
   {

         //在指定砖块层数生成道具
         if ((this.currType==Brickprop_Type.Prop_Life||this.currType==Brickprop_Type.Prop_More) && brickLayer==health)
         {
            GenerateProp();
         }
      
   }

   private void OnCollisionEnter2D(Collision2D collision)
   {
      Ball ball = collision.gameObject.GetComponent<Ball>();
      Brick brick = collision.otherCollider.gameObject.GetComponent<Brick>();
      
      if (ball != null)
      {
         Hit();
      }
   }

   /// <summary>
   /// 生成道具
   /// </summary>
   private void GenerateProp()
   {
      GameObject item = Instantiate(propPrefab);
      Vector3 pos = transform.position;
      pos.z -= 0.5f;
      item.transform.position = pos;

   }
}
